package com.opg.uop.manage.security.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.opg.uop.manage.system.model.User;
import com.opg.uop.manage.system.service.UserService;


//@Controller
//@RequestMapping("security")
public class SecurityController {
	
	private final Logger LOGGER = LoggerFactory.getLogger(SecurityController.class);
	
//	@Autowired
//	private UserService userService;

	@RequestMapping(value = "toLogin")
	public ModelAndView toLogin(){
		//判断用户是否登录 如果登录了直接跳转到main页面
		if(null == SecurityUtils.getSubject().getPrincipal()){
			return new ModelAndView("/login/login");
		}
		return new ModelAndView("redirect:/Permission/toPermission.do");
	}
	
	@RequestMapping(value = "login")
	public ModelAndView login(String username, String password,
			HttpServletRequest request, HttpServletResponse reponse){
		String msg = "";
		Map<String,String> map = new HashMap<String,String>();
		if(StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)){
			UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password));
			token.setRememberMe(false);
			Subject subject = SecurityUtils.getSubject();
			try{
				subject.login(token);
				if(subject.isAuthenticated()){
					subject.hasRole("");
					return new ModelAndView("redirect:/main/toMain.do");
				}
				msg = "登录成功！";
				map.put("success", "true");
			} catch (IncorrectCredentialsException e) {
		        msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";
		        map.put("success", "false");
		    } catch (ExcessiveAttemptsException e) {
		        msg = "登录失败次数过多";
		        map.put("success", "false");
		    } catch (LockedAccountException e) {
		        msg = "帐号已被锁定. The account for username " + token.getPrincipal() + " was locked.";
		        map.put("success", "false");
		    } catch (DisabledAccountException e) {
		        msg = "帐号已被禁用. The account for username " + token.getPrincipal() + " was disabled.";
		        map.put("success", "false");
		    } catch (ExpiredCredentialsException e) {
		        msg = "帐号已过期. the account for username " + token.getPrincipal() + "  was expired.";
		        map.put("success", "false");
		    } catch (UnknownAccountException e) {
		        msg = "帐号不存在. There is no user with username of " + token.getPrincipal();
		        map.put("success", "false");
		    } catch (UnauthorizedException e) {
		        msg = "您没有得到相应的授权！" + e.getMessage();
		        map.put("success", "false");
		    }
			map.put("message", msg);
		}else{
			msg = "用户名或密码不能为空！";
			map.put("success", "false");
		}
		return new ModelAndView("/login/login", map);
	}
	
	@RequestMapping(value = "logout")
	public ModelAndView logout() {
        try {
            Subject subject = SecurityUtils.getSubject();
            String userName = SecurityController.getLoginUser().getLoginName();
            subject.logout();
            LOGGER.info("User logout.", userName);
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
        return new ModelAndView("login");
    }

    public static User getLoginUser() {
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            return null;
        }
        return (User) subject.getPrincipal();
    }
    
    public static Map<String, List<Integer>> getLoginUserPermission() {
    	Set<String> roleNames = new HashSet<String>();
    	Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()){
            return null;
        }
        roleNames.add(((User) subject.getPrincipal()).getLoginName());
        Set<String> permissions = new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        permissions = info.getStringPermissions();
        Map<String, List<Integer>> perMap = new HashMap<String, List<Integer>>();
        for(String permission : permissions){
        	System.out.println(permission);
        }
        return null;
    }
}
